package com.atguigu.practice;

import java.util.ArrayList;

class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}
public class CheckPalindrome {
    public static void main(String[] args) {
        ListNode head=new ListNode(1);
        head.next=new ListNode(2);
        head.next.next=new ListNode(3);
        head.next.next.next=new ListNode(4);
        head.next.next.next.next=new ListNode(5);
        boolean flag=isPalindromeLinkedList(head);
        System.out.println(flag);
    }
    public static boolean isPalindromeLinkedList(ListNode head){
        if(head==null&&head.next==null){
            return true;
        }
        ArrayList<Integer> list=new ArrayList<>();
        ListNode cur=head;
        while(cur!=null){
            list.add(cur.val);
            cur=cur.next;
        }
        //此时将链表进行逆转
        ListNode reverseHead=reverseList(head);
        cur=reverseHead;
        int i=0;
        while(cur!=null){
            int val=cur.val;
            if(val!=list.get(i)){
                return false;
            }
            i++;
            cur=cur.next;
        }
        return true;
    }
    public static ListNode reverseList(ListNode head){
        ListNode cur=head.next;
        head.next=null;
        while(cur!=null){
            ListNode node=cur;
            cur=cur.next;
            node.next=head;
            head=node;
        }
        return head;
    }
}
